package com.alibaba.gao.delayQueue.processor;

import com.alibaba.gao.delayQueue.RedisDelayQueueBizService;
import com.alibaba.gao.delayQueue.RedisDelayQueueEnum;
import com.alibaba.gao.delayQueue.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * Title:启动类
 * </p>
 * <p>
 * Description:redis延迟队列服务启动类
 * </p>
 * <p>
 * Copyright: 2020~2021
 * </p>
 * <p>
 * Company/Department: EnnCloud
 * </p>
 *
 * @author zhangyiwu <b>Creation Time:</b> 2021-11-22 15:21:04
 * @since V1.0
 */
@Slf4j
@Component
public class RedisDelayQueueRunner implements CommandLineRunner {

    @Resource
    private RedisDelayQueueBizService redisDelayQueueBizService;

    @Override
    public void run(String... args) {
        log.info("===============redis延迟队列初始化开始==============");
        RedisDelayQueueEnum[] queueEnums = RedisDelayQueueEnum.values();
        for (RedisDelayQueueEnum queueEnum : queueEnums) {
            log.info("启动延迟队列，队列名：{}", queueEnum.getName());
            Thread thread = new Thread(() -> {
                while (true) {
                    try {
                        Object value = redisDelayQueueBizService.getDelayQueue(queueEnum.getCode());
                        if (value != null) {
                            RedisDelayQueueHandler<Object> redisDelayQueueHandler =
                                SpringContextUtil.getBean(queueEnum.getBeanId(), RedisDelayQueueHandler.class);
                            redisDelayQueueHandler.execute(value);
                        }
                    } catch (Exception e) {
                        log.warn("延迟队列处理异常。", e);
                    }
                }
            });
            thread.setName(queueEnum.getCode());
            thread.start();
        }
        // 启动成功后往redis中压入一个空对象
        redisDelayQueueBizService.addDelayQueue(new HashMap<>(), 5, TimeUnit.SECONDS,
            RedisDelayQueueEnum.ORDER_NOT_ACCEPTED.getCode());
        log.info("===============redis延迟队列初始化结束==============");
    }
}
